/**
 * 
 */
package dao.versant;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.jdo.Query;

import tp.model.Client;
import tp.model.Ticket;
import tp.model.Train;
import dao.interfaces.IClientDAO;

/**
 * @author Admin
 * 
 */
public class ClientDAOVersant extends VersantDAO<Client> implements IClientDAO {

	@Override
	public Client find(String nomClient) {
		Query q = pm.newQuery(Client.class);
		q.declareParameters("String client");
		q.setFilter("nom == client");
		Client client = null;
		Collection collection;
		try {
			collection = (Collection) q.execute(nomClient);
			System.out.println(collection);
			if (!collection.isEmpty()) {
				Iterator i = collection.iterator();
				if (i.hasNext())
					client = (Client) i.next();
			}
		} finally {
			if (client != null)
				q.close(client);
		}
		return client;
	}

	@Override
	public void create(Client client) {
		pm.currentTransaction().begin();
		pm.makePersistent(client);
		pm.currentTransaction().commit();
	}

	@Override
	public void updateTicket(Client client, Ticket ticket) {
		// TODO Auto-generated method stub
		pm.currentTransaction().begin();
		Client clientPersistant = this.find(client.getNom());
		Ticket ticketPersistant = this.findTicket(ticket.getNom());
		clientPersistant.getTickets().add(ticketPersistant);
		pm.currentTransaction().commit();
	}
	
	private Ticket findTicket(String ticketNom) {
		// TODO Auto-generated method stub
		Query q = pm.newQuery(Ticket.class);
		q.declareParameters("String t");
		q.setFilter("nom == t");
		Ticket ticket = null;
		Collection collection;
		try {
			collection = (Collection) q.execute(ticketNom);
			if (!collection.isEmpty()) {
				Iterator i = collection.iterator();
				if (i.hasNext())
					ticket = (Ticket) i.next();
			}
		} finally {
			if (ticket != null)
				q.close(ticket);
		}
		return ticket;	
	}

	@Override
	public ArrayList<Client> findAll() {
		return null;
	}

	@Override
	public void delete(Client obj) {

	}

	@Override
	public void deleteTicket(Client client, Ticket ticket) {
		// TODO Auto-generated method stub
		
	}

}
